import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.Socket;

public class Publisher extends Thread{
    public static void main(String...args){
        try {
            Address trackerAddress = new Address("127.0.0.1",1234);
            InputStream inputStream = Publisher.class.getClassLoader().getResourceAsStream("twoParties.png");
            Integer imageSize = inputStream.available();
            System.out.println("图片文件大小: " + imageSize + " 字节");

            Torrent torrent = new Torrent("twoParties",trackerAddress);
            torrent.setLength(imageSize);
            torrent.setTrackerAddress(trackerAddress);

            Socket socket = trackerAddress.connectToAddress();
            Message message = new Message("addSource");
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            /*发布资源*/
            out.println(JSONObject.toJSONString(message));
            while(true){
                try {
                    Message receiveMessage = JSONObject.parseObject(in.readLine(), Message.class);
                    System.out.println(receiveMessage);
                    if(receiveMessage.operation.equals("generatedTorrentIndex")){
                        torrent.setIndex(receiveMessage.index);
                        System.out.println("种子打包成功!资源号为"+torrent.getIndex());
                    }
                    sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
